package com.hx.demo.handle;

import com.alibaba.fastjson.JSONObject;
import com.hx.demo.util.AjaxResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MyFailSecurityHandle extends SimpleUrlAuthenticationFailureHandler {


    /**
     * 所有的web 技术栈都是基于 servlet 协议，大家实现这个标准
     * @param request
     * @param response
     * @param exception  登录失败的原因
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        AjaxResult ajaxResult = AjaxResult.error(exception.getMessage());
        printWriter.append(JSONObject.toJSONString(ajaxResult));
        printWriter.close();
    }
}
